import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'dart:convert';
import 'package:flutter_shop/model/cartInfo.dart';

///思路：
///由于SharedPreference无法存储map数组因此将map数组变成string存储
///取出时将String转换为map数组使用
class CartProvide with ChangeNotifier {
  String cartString = '[]';
  List<CartInfoModel> cartList = [];

  //商品总价格
  double totalPrice = 0;

  //商品数量
  int totalGoodsCount = 0;

  //是否全选的按钮标志
  bool isAllCheck = true;

  save(goodsId, goodsName, count, price, images) async {
    SharedPreferences sharedPreferences = await SharedPreferences.getInstance();
    //取出String
    cartString = sharedPreferences.get('cartInfo');
    //将string装换为map数组
    var temp = cartString == null ? [] : json.decode(cartString.toString());
    //强制转换为map数组
    List<Map> tempList = List<Map>.from(temp);
    //标志这个商品在购物车中是否已经存在
    bool isHave = false;
    /*
    tempList.forEach((item) {
      if (item['goodsId'] == goodsId) {
        item['count']++;
        isHave = true;
      }
    });
    */

    //为了点击购买时能够正确显示购物车商品数量
    totalPrice = 0;
    totalGoodsCount = 0;

    //第二种遍历方法找到对应id就退出循环效率更高后续为了处理购物车商品数量显进行修改
    for (int index = 0; index < tempList.length; index++) {
      if (tempList[index]['goodsId'] == goodsId) {
        tempList[index]['count']++;
        cartList[index].count++;
        isHave = true;
//        break;
      }
      if (cartList[index].isCheck) {
        totalPrice += cartList[index].price * cartList[index].count;
        totalGoodsCount += cartList[index].count;
      }
    }
    //如果不存在则加入
    if (!isHave) {
      Map<String, dynamic> newGoods = {
        'goodsId': goodsId,
        'goodsName': goodsName,
        'count': count,
        'price': price,
        'images': images,
        'isCheck': true
      };
      tempList.add(newGoods);

      cartList.add(CartInfoModel.fromJson(newGoods));

      totalPrice += count * price;
      totalGoodsCount += count;
    }

    //将map数组变成字符串
    cartString = json.encode(tempList).toString();
    sharedPreferences.setString('cartInfo', cartString);
    notifyListeners();
  }

  remove() async {
    SharedPreferences sharedPreferences = await SharedPreferences.getInstance();
    sharedPreferences.remove('cartInfo');
    totalGoodsCount = 0;
    totalPrice = 0;
    cartList.clear();
    notifyListeners();
  }

  getCartInfo() async {
    SharedPreferences sharedPreferences = await SharedPreferences.getInstance();
    //取出数据
    cartString = sharedPreferences.get('cartInfo');
    //先清空数据
    cartList.clear();
    //数据不为空的时候
    if (cartString != null) {
      //将数据取出成List<Map>
      List<Map> tempList = List<Map>.from(json.decode(cartString.toString()));

      //每次初始化为0
      totalPrice = 0;
      totalGoodsCount = 0;

      //全选状态每次或得列表时初始化
      isAllCheck = true;

      tempList.forEach((item) {
        if (item['isCheck']) {
          totalPrice += (item['price'] * item['count']);
          totalGoodsCount += item['count'];
        } else {
          isAllCheck = false;
        }
        cartList.add(CartInfoModel.fromJson(item));
      });
    }
    notifyListeners();
  }

  //删除单个购物车商品
  deleteOneGoods(String goodsId) async {
    SharedPreferences sharedPreferences = await SharedPreferences.getInstance();
    cartString = sharedPreferences.getString('cartInfo');
    List<Map> tempList = List<Map>.from(json.decode(cartString));

    //遍历寻找是要删除的goodsId所在的下标
    int deleteIndex = 0;
    for (int index = 0; index < tempList.length; index++) {
      if (tempList[index]['goodsId'] == goodsId) {
        deleteIndex = index;
        break;
      }
    }
    tempList.removeAt(deleteIndex);
    //重新持久化
    cartString = json.encode(tempList).toString();
    sharedPreferences.setString('cartInfo', cartString);
    //重新获取数据
    await getCartInfo();
  }

  //改变选中按钮的状态
  changeCheckBox(String goodsId) async {
    SharedPreferences sharedPreferences = await SharedPreferences.getInstance();
    cartString = sharedPreferences.getString('cartInfo');
    List<Map> tempList = List<Map>.from(json.decode(cartString));
    //遍历当前点击的item
    for (int index = 0; index < tempList.length; index++) {
      if (tempList[index]['goodsId'] == goodsId) {
        tempList[index]['isCheck'] = !tempList[index]['isCheck'];
        break;
      }
    }
    //重新持久化
    cartString = json.encode(tempList).toString();
    sharedPreferences.setString('cartInfo', cartString);
    //重新获取数据
    await getCartInfo();
  }

  //全选按钮效果的实现
  changeAllCheckSate(bool isCheck) async {
    SharedPreferences sharedPreferences = await SharedPreferences.getInstance();
    cartString = sharedPreferences.getString('cartInfo');
    List<Map> tempList = List<Map>.from(json.decode(cartString));
    //遍历当前点击的item
    for (int index = 0; index < tempList.length; index++) {
      tempList[index]['isCheck'] = isCheck;
    }
    //重新持久化
    cartString = json.encode(tempList).toString();
    sharedPreferences.setString('cartInfo', cartString);
    //重新获取数据
    await getCartInfo();
  }

  //商品加减方法
  addOrReduce(String goodsId, String todo) async {
    SharedPreferences sharedPreferences = await SharedPreferences.getInstance();
    cartString = sharedPreferences.getString('cartInfo');
    List<Map> tempList = List<Map>.from(json.decode(cartString));
    //记录操作项的下标
    int addOrReduceIndex = 0;
    for (int index = 0; index < tempList.length; index++) {
      if (tempList[index]['goodsId'] == goodsId) {
        addOrReduceIndex = index;
        break;
      }
    }

    if (todo == 'add') {
      tempList[addOrReduceIndex]['count']++;
    } else if (tempList[addOrReduceIndex]['count'] > 1) {
      tempList[addOrReduceIndex]['count']--;
    }

    //重新持久化
    cartString = json.encode(tempList).toString();
    sharedPreferences.setString('cartInfo', cartString);
    //重新获取数据
    await getCartInfo();
  }
}
